package com.alternatealerts.client;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.Toast;

public class Main extends Activity {
	
	private static final String TAG = "MainActivity";
	private ArrayList<Alert> alerts;
	private AlertsArrayAdapter alertsAdapter;
	private ArrayList<Station> stations;
	private ArrayAdapter<Station> stationAdapter;
	private ListView alertListView;
	private Spinner stationSpinner;
	private Station station;
	private int ADD_NEW_TAB = Menu.FIRST;
	
	
	public String getMyPhoneNumber()
    {
        return ((TelephonyManager) getSystemService(TELEPHONY_SERVICE))
                .getLine1Number();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        TabHost tabs = (TabHost) this.findViewById(R.id.my_tabhost);
        tabs.setup();
        TabSpec tspec1 = tabs.newTabSpec("First Tab");
        tspec1.setIndicator("Alert Log");
        tspec1.setContent(R.id.TableLayout1);
        tabs.addTab(tspec1);
        TabSpec tspec2 = tabs.newTabSpec("Second Tab");
        tspec2.setIndicator("Two");
        tspec2.setContent(R.id.TableLayout1);
        tabs.addTab(tspec2);
        TabSpec tspec3 = tabs.newTabSpec("Third Tab");
        tspec3.setIndicator("Three");
        tspec3.setContent(R.id.TableLayout1);
        tabs.addTab(tspec3);
        
        stations = new ArrayList<Station>();
        alerts = new ArrayList<Alert>();
        setupAlertsListView();
        setupStationSpinner();
    }
    private void setupStationSpinner(){
    	// Temp spinner items. 
    	stations.add(new Station("Station Name", 1));
    	stationAdapter = new ArrayAdapter<Station>(this, android.R.layout.simple_spinner_dropdown_item, stations);
    	try{
    		stationSpinner = (Spinner)findViewById(R.id.stationSpinner);
    		stationSpinner.setAdapter(stationAdapter);
    		stationSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){

				public void onItemSelected(AdapterView<?> adapter, View view,
						int posistion, long id) {
					// Auto-generated method stub
					station = (Station) adapter.getItemAtPosition(posistion);
					new RetrieveStationAlertsTask().execute(station);
				}

				public void onNothingSelected(AdapterView<?> arg0) {
					// not used
					
				}
    			
    		});
    	} catch (Exception e){
    		e.printStackTrace();
    	}
    	
    }
	private void setupAlertsListView() {
		alertListView = (ListView)findViewById(R.id.alertListView);
        alertsAdapter = new AlertsArrayAdapter(this, R.layout.alert_item, alerts);
        alertListView.setAdapter(alertsAdapter);
        alertListView.setOnItemClickListener(new OnItemClickListener(){

			public void onItemClick(AdapterView<?> adapter, View view, int position,
					long id) {
				Alert alert = (Alert)adapter.getItemAtPosition(position);
				// TODO Start activity to retrieve the MP3 file and play the audio.
				new PlayRecordingTask().execute(alert.getRecordingId());
			}
        	
        });
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	menu.add(0, ADD_NEW_TAB, 0, "New Tabs");
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    @Override
	protected void onResume() {
		super.onResume();
		// Lookup the alert items from the webservice as a background task
		new RetrieveStationsTask().execute();
		new RetrieveStationAlertsTask().execute();
	}
    private class PlayRecordingTask extends AsyncTask<Long, Void, byte[]>{

		@Override
		protected byte[] doInBackground(Long... arg0) {
			// TODO Auto-generated method stub
			long recordingId = arg0[0];
			byte[] recording;
			recording = DAO.getRecording(recordingId);
			return recording;
		}

		@Override
		protected void onPostExecute(byte[] result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			playMp3(result);
		}
		
    	
    }
    private class RetrieveStationsTask extends AsyncTask<Long, Void, Void>{

		@Override
		protected Void doInBackground(Long... params) {
			// Retrieve a list of stations
			stations.clear();
			stations.add(new Station("Filter by Station", 0));
			for(Station s : DAO.getStations()){
				stations.add(s);
			}
			if (stations.size() == 1){
				stations.add(new Station("No Stations Found", 0));
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// Update the adapter
			super.onPostExecute(result);
			stationAdapter.notifyDataSetChanged();
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}
    	
    }
	private class RetrieveStationAlertsTask extends AsyncTask<Station, Void, Void>{

		@Override
		protected Void doInBackground(Station... params) {
			Station station = new Station();
			try{
				station = (Station) params[0];	
				Log.d(TAG, "Looking up station ID " + station.getStationId());
				
			} catch (Exception e){
				e.printStackTrace();
				Log.e(TAG, "No station id was passed to background task");
			}
			
			// Clear the list of alerts to make way for the new ones
			if (station.getStationId() > 0){
				alerts.clear();
				// TODO Lookup the specific station id recording alert list
				for (Alert a : DAO.getStationAlerts(station)){
					alerts.add(a);
				}
			} else {
				// TODO look up the list of alerts regardless of station
				for (Alert a : DAO.getAlerts()){
					alerts.add(a);
				}
				if(alerts.isEmpty()){
					// Add item
					alerts.add(new Alert("Not Alerts Found", new Date(), 0));
				}
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// Update the arrayadapter of the new content
			super.onPostExecute(result);
			alertsAdapter.notifyDataSetChanged();
		}

		@Override
		protected void onPreExecute() {
			// TODO What to do before the list of results is retrieved
			super.onPreExecute();
			Toast.makeText(Main.this, "Retrieving Alerts", Toast.LENGTH_LONG).show();
		}
    	
    }
	private void playMp3(byte[] mp3SoundByteArray) {
	    try {
	        // create temp file that will hold byte array
	        File tempMp3 = File.createTempFile("kurchina", "mp3", getCacheDir());
	        tempMp3.deleteOnExit();
	        FileOutputStream fos = new FileOutputStream(tempMp3);
	        fos.write(mp3SoundByteArray);
	        fos.close();

	        // Tried reusing instance of media player
	        // but that resulted in system crashes...  
	        MediaPlayer mediaPlayer = new MediaPlayer();

	        // Tried passing path directly, but kept getting 
	        // "Prepare failed.: status=0x1"
	        // so using file descriptor instead
	        FileInputStream fis = new FileInputStream(tempMp3);
	        mediaPlayer.setDataSource(fis.getFD());
	        mediaPlayer.prepare();
	        mediaPlayer.start();
	        fis.close();
	    } catch (IOException ex) {
	        String s = ex.toString();
	        ex.printStackTrace();
	    }
	}

}
